package com.pure.database.ui.component

import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.google.gson.Gson
import com.pure.database.objectbox.ObjectBox
import com.pure.database.objectbox.entity.Food
import com.pure.database.objectbox.entity.Order
import com.pure.database.objectbox.entity.Order_
import com.pure.database.objectbox.entity.User
import com.pure.database.objectbox.entity.User_
import com.pure.database.ui.common.style.NormalButton
import kotlin.random.Random

/**
 * FileName : ObjectBoxTest
 * Author : luqihua
 * Date : 2025/3/20
 * Desc :
 **/
private const val TAG = "ObjectBoxTest"

@Composable
fun ObjectBoxTest(modifier: Modifier = Modifier) {
    val randomLong = Random(1)
    Column {
        NormalButton(text = "插入用户") {
            val user1 = User(name = "张三", age = 18)
            user1.orders.add(Order(price = randomLong.nextLong()).also {
                it.foods.add(Food(name = "香蕉", price = "10.9"))
                it.foods.add(Food(name = "苹果", price = "12"))
            })
            val userBox = ObjectBox.get()?.boxFor(User::class.java)


//            val moshi = Moshi.Builder().build()
//            val adapter = moshi.adapter<User>(User::class.java)
//            val json = adapter.toJson(user1)
            val json = Gson().toJson(user1)
            Log.d(TAG, "ObjectBoxTest: json=$json")
            Log.d(TAG, "TestDataBasePage: insert id=${userBox?.put(user1)}")
        }

        NormalButton(text = "查询User") {
            val userBox = ObjectBox.get()?.boxFor(User::class.java)
            userBox?.all?.forEach {
                Log.d(TAG, "user = $it")
            }
        }

        NormalButton(text = "删除User") {
            val userBox = ObjectBox.get()?.boxFor(User::class.java)
            userBox?.let {
                it.query().equal(User_.id, 1).build().remove()
            }
        }

        NormalButton(text = "插入订单") {
            val food1 = Food(name = "香蕉", price = "10.9")
            val food2 = Food(name = "苹果", price = "12")

            val order = Order(price = 1000).also {
                it.foods.add(food1)
                it.foods.add(food2)
            }

            ObjectBox.get()?.boxFor(Order::class.java)?.put(order)

        }

        NormalButton(text = "查询订单") {
            ObjectBox.get()?.boxFor(Order::class.java)?.let { box ->
                box.query().equal(Order_.userId, 3).build().find().forEach {
                    Log.d(TAG, "order = $it")
                }
            }
        }
    }
}